package com.dz.lm.service.comp.user.impl;

import com.dz.lm.common.dto.*;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.MD5Util;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.compuser.write.CompUserDao;
import com.dz.lm.dao.product.read.CommonAreaDao;
import com.dz.lm.dao.useragent.read.UserAgentDao;
import com.dz.lm.dao.userapply.read.UserApplyDao;
import com.dz.lm.dao.userproduct.read.UserProductDao;
import com.dz.lm.domain.comp.Comp;
import com.dz.lm.domain.compaccount.CompAccount;
import com.dz.lm.domain.compremark.CompRemark;
import com.dz.lm.domain.comprole.CompRole;
import com.dz.lm.domain.compuser.CompUser;
import com.dz.lm.domain.compuser.CompUserExample;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.domain.userapply.UserApply;
import com.dz.lm.domain.userapply.UserApplyExample;
import com.dz.lm.domain.userproduct.UserProduct;
import com.dz.lm.service.agentreview.AgentReviewService;
import com.dz.lm.service.appLogin.AppLoginService;
import com.dz.lm.service.comp.comp.CompService;
import com.dz.lm.service.comp.account.CompAccountService;
import com.dz.lm.service.comp.remark.CompRemarkService;
import com.dz.lm.service.comp.role.CompRoleService;
import com.dz.lm.service.comp.user.CompUserService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userproduct.UserProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartlbs.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompUserServiceImpl implements CompUserService {
    @Resource(name = "readCompUserDao")
    private com.dz.lm.dao.compuser.read.CompUserDao readCompUserDao;

    @Resource(name = "writeCompUserDao")
    private CompUserDao writeCompUserDao;
    @Autowired
    private UserApplyService userApplyService;
    @Autowired
    private CompService compService;
    @Autowired
    private AppLoginService appLoginService;
    @Autowired
    private CompRoleService compRoleService;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;
    @Resource(name = "readUserApplyDao")
    private UserApplyDao readUserApplyDao;
    @Resource(name = "readUserProductDao")
    private UserProductDao readUserProductDao;
    @Resource(name = "readUserAgentDao")
    private UserAgentDao readUserAgentDao;
    @Autowired
    private UserProductService userProductService;
    @Autowired
    private CompAccountService compAccountService;
    @Autowired
    private CommonAreaDao readCommonAreaDao;
    @Autowired
    private AgentReviewService agentReviewService;
    @Autowired
    private CompRemarkService compRemarkService;
    @Override
    public int register(String phone, String password, int compId, int roleId) throws ServiceException {
        Map qryParam = new HashMap();
        qryParam.put("mobilePhone", phone);
        qryParam.put("password", password);
        try {
            password = MD5Util.MD5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> user = appLoginService.qryUserInfo(qryParam);
        if (user == null || user.isEmpty()) { //用户不存在
            return -997;

        } else if (!password.equals(user.get("passWord"))) { //密码错误
            return -998;
        }
        int userId = StringUtil.getInt(user.get("userId"), 0);
        CompUserExample ex = new CompUserExample();
        CompUserExample.Criteria cr = ex.createCriteria();
        cr.andUserIdEqualTo(userId);
        cr.andCompIdEqualTo(compId);
        cr.andStatusNotEqualTo(2);//审核未通过
        try {
            List<CompUser> compUsers = readCompUserDao.selectByExample(ex);
            if(compUsers != null && compUsers.size() > 0){
                return  -996;
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        CompUser compUser = new CompUser();
        compUser.setUserId(userId);
        compUser.setCompId(compId);
        compUser.setRoleId(roleId);
        compUser.setStatus(0);
        try {
            compUser.setCreateTime(DateUtil.getNowDateTimeString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return writeCompUserDao.insertSelective(compUser);
    }

    @Override
    public int reivew(int pid, int satuts ,int roleId) throws ServiceException {
        CompUser compUser = new CompUser();
        compUser.setpId(pid);
        compUser.setStatus(satuts);
        if(roleId > 0){
            compUser.setRoleId(roleId);
        }
        return writeCompUserDao.updateByPrimaryKeySelective(compUser);
    }

    @Override
    public int delete(int pid) throws ServiceException {
        return writeCompUserDao.deleteByPrimaryKey(pid);
    }

    @Override
    public PageDto query(int pageNum, int rows, int compId, int roleId, int status) throws ServiceException {
        PageHelper.startPage(pageNum, rows);
        PageDto pageDto = new PageDto();
        CompUserExample ex = new CompUserExample();
        ex.setOrderByClause("status asc");
        CompUserExample.Criteria cr = ex.createCriteria();
        if (compId > 0) {
            cr.andCompIdEqualTo(compId);
        }
        if(roleId > 0){
            cr.andRoleIdEqualTo(roleId);
        }
        if (status > -1) {
            cr.andStatusEqualTo(status);
        }
        List<CompUser> users = null;
        try {
            users = readCompUserDao.selectByExample(ex);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        if (users != null && users.size() > 0) {
            List<CompUserDTO> dtos = new ArrayList();
            PageInfo pageInfo = new PageInfo(users);
            for (CompUser user : users) {
                CompUserDTO dto = new CompUserDTO();
                BeanUtils.copyProperties(user, dto);
                setExt(dto);
                dtos.add(dto);
            }
            pageDto.setInfo(pageInfo);
            pageDto.setList(dtos);
        }
        return pageDto;
    }

    private void setExt(CompUserDTO dto) throws ServiceException {
        if (dto.getRoleId() > 0) {
            CompRole compRole = compRoleService.get(dto.getRoleId());
            if (compRole != null) {
                dto.setRoleName(compRole.getName());
            }
        }
        if (dto.getUserId() > 0) {
            Map p1 = new HashMap();
            p1.put("userId", dto.getUserId());
            Map user = null;
            try {
                user = rAppLoginDao.qryUserInfoByUserId(p1);
            } catch (DaoException e) {
                e.printStackTrace();
            }
            if (user != null) {
                dto.setName(StringUtil.getString(user.get("lName")) + "/" + StringUtil.getString(user.get("uName")));
                dto.setLname(StringUtil.getString(user.get("lName")));
                dto.setuName(StringUtil.getString(user.get("uName")));
            }
        }


    }

    @Override
    public PageDto queryApply(int pageNum, int rows, int userId, int compId, String name, int roleId, String province, int status) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(pageNum, rows);
        Map map = new HashMap();
        if (userId > 0) {
            map.put("userId", userId);
        }
        if (roleId > 0) {
            map.put("roleId", roleId);
        }
        if(!StringUtil.containEmpty(name)){
            map.put("name", name);

        }
        if (!StringUtil.containEmpty(province)) {
            map.put("province", province);
        }
        if (status > 0) {
            map.put("status", status);
        }
        if (compId > 0) {
            map.put("compId", compId);
        }
        try {
            List<UserApply> userApplies = readUserApplyDao.queryUser(map);
            int i = readUserApplyDao.queryUserCount(map);
            pageDto.setCount(i);
            if (userApplies != null && userApplies.size() > 0) {
                List<UserApplyDTO> dtos = new ArrayList();
                PageInfo pageInfo = new PageInfo(userApplies);
                for (UserApply apply : userApplies) {
                    UserApplyDTO dto = new UserApplyDTO();
                    BeanUtils.copyProperties(apply, dto);
                    try {
                        setApplyExt(dto, compId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dtos.add(dto);
                }
                pageDto.setList(dtos);
                pageDto.setInfo(pageInfo);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return pageDto;
    }

    private void setApplyExt(UserApplyDTO dto, int compId) throws Exception {
        //发布者
        CompUserDTO compUser = this.get(dto.getSupUserId(), compId, 0);
        dto.setCompUser(compUser);
        //申请人
        Map p1 = new HashMap();
        p1.put("userId", dto.getSubUserId());
        Map user = rAppLoginDao.qryUserInfoByUserId(p1);
        dto.setSubUser(user);
        //产品信息
        UserProductDTO detail = userProductService.getDetail(0, dto.getProductId(), false);
        Map product = new HashMap();
        product.put("productName", detail.getProductName());
        product.put("productId", detail.getProductId());
        dto.setProduct(product);
        dto.setCreateTime(dto.getCreateTime().substring(0, dto.getCreateTime().length() - 3));
        //代理人信息
        if (dto.getAgentUid() > 0) {
            p1.clear();
            p1.put("userId", dto.getAgentUid());
            Map agentUser = rAppLoginDao.qryUserInfoByUserId(p1);
            dto.setAgentUser(agentUser);
        }
        //填充地区
        //adress
        if(!StringUtil.containEmpty(dto.getProvince())){
            CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getProvince()));
            CommonArea city = null;
            CommonArea area = null;
            if (!StringUtils.isEmpty(dto.getCity())) {
                city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getCity()));
            }
            if(!StringUtil.containEmpty(dto.getArea())){
                area = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getCity()));
            }
            String provinceName = province != null ? province.getName():"";
            String cityName = city!= null ?city.getName() :"";
            String areaName = area!= null ?area.getName() :"";
            String adress = provinceName+cityName+areaName;
            dto.setAddress(adress);
        }
        //填充备注信息
        CompRemark remark = compRemarkService.get(dto.getApplyId(), 1);
        if(remark != null){
            dto.setCompRemark(remark);
        }
    }

    @Override
    public PageDto queryAgent(int pageNum ,int rows,int userId ,int compId ,String name ,String mobilePhone,int roleId , String province , String prouductName,String time,int agentType) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(pageNum, rows);
        Map map = new HashMap();
        if (userId > 0) {
            map.put("userId", userId);
        }
        if (roleId > 0) {
            map.put("roleId", roleId);
        }
        if (!StringUtil.containEmpty(province)) {
            map.put("province", province);
        }
        if(!StringUtil.containEmpty(mobilePhone)){
            map.put("mobilePhone",mobilePhone);
        }
        if(!StringUtil.containEmpty(time)){
            map.put("time",time);
            map.put("subTime",time+" 00:00:00");
            map.put("subTime",time+" 23:59:59");
        }
        if (agentType > 0) {
            map.put("status", agentType);
        }
        if (compId > 0) {
            map.put("compId", compId);
        }
        if(!StringUtil.containEmpty(name)){
            map.put("name", name);
        }
        if(!StringUtil.containEmpty(prouductName)){
            map.put("productName",prouductName);
        }
        List<UserProduct> Products = null;
        try {
            Products = readUserProductDao.queryaAgentUser(map);
            int i = readUserProductDao.queryaAgentUserCount(map);
            pageDto.setCount(i);
            if (Products != null && Products.size() > 0) {
                PageInfo pageInfo = new PageInfo(Products);
                List<UserProductDTO> dtos = new ArrayList();
                for (UserProduct product : Products) {
                    UserProductDTO dto = new UserProductDTO();
                    BeanUtils.copyProperties(product, dto);
                    try {
                        setAgentExt(dto, compId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dtos.add(dto);
                }
                pageDto.setInfo(pageInfo);
                pageDto.setList(dtos);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return pageDto;
    }

    private void setAgentExt(UserProductDTO dto, int compId) throws Exception {
        //发布者
        CompUserDTO user = this.get(dto.getSource(), compId, 0);
        dto.setSourceProduct(user);
        //代理人
        Map p1 = new HashMap();
        p1.put("userId", dto.getUserId());
        Map agnetuser = rAppLoginDao.qryUserInfoByUserId(p1);
        if(agnetuser != null){
            dto.setUser(agnetuser);
        }
        //总金额和总代理返点金额
        Map map = new HashMap();
        map.put("productId",dto.getSuperId());
        map.put("agentUid",dto.getUserId());
        readUserApplyDao.queryaAgentUserAmount(map);
        dto.setAmounts(StringUtil.getDouble(map.get("amount"),0));
        dto.setRePoints(StringUtil.getDouble(map.get("rePoint"),0));
        //历史订单
        dto.setApplyCount(userApplyService.querCount(0, 0,dto.getUserId(), dto.getProductType() ==1 ?dto.getProductId():dto.getSuperId(), 0, false,false,false,0,0));
        //地区
        //adress
        CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getProvince()));
        String provinceName = province != null ? province.getName():"";
        String adress = provinceName;
        dto.setAddress(adress);

        //填充申请信息
        AgentReviewDTO review = agentReviewService.get(0, dto.getProductId(), false);
        if(review != null){
            dto.setAgentReivew(review);
        }
        dto.setCreateTime(dto.getCreateTime().substring(0,10));
        //填充备注信息
        CompRemark remark = compRemarkService.get(dto.getProductId(), 2);
        if(remark != null){
            dto.setCompRemark(remark);
        }
    }

    @Override
    public CompUserDTO get(int userId, int compId ,int pid) throws ServiceException {
        CompUserDTO dto = null;
        CompUserExample ex = new CompUserExample();
        CompUserExample.Criteria cr = ex.createCriteria();
        if (pid > 0) {
            cr.andPIdEqualTo(pid);
        } else {
            if (userId > 0) {
                cr.andUserIdEqualTo(userId);
            }
            if (compId > 0) {
                cr.andCompIdEqualTo(compId);
            }
        }
        try {
            List<CompUser> users = readCompUserDao.selectByExample(ex);
            if (users != null && users.size() > 0) {
                dto = new CompUserDTO();
                CompUser user = users.get(0);
                BeanUtils.copyProperties(user, dto);
                setExt(dto);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return dto;
    }

    @Override
    public UserApplyDTO getApplyDetail(int applyId, int compId) throws ServiceException {
        UserApplyDTO dto = null;
        UserApply userApply = null;
        try {
            userApply = readUserApplyDao.selectByPrimaryKey(applyId);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        if (userApply != null) {
            dto = new UserApplyDTO();
            BeanUtils.copyProperties(userApply, dto);
            try {
                setApplyExt(dto, compId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dto;
    }

    @Override
    public UserProductDTO getAgentDetail(int productId, int compId) throws ServiceException {
        UserProductDTO dto = null;
        try {
            UserProduct userProduct = readUserProductDao.selectByPrimaryKey(productId);
            if(userProduct != null){
                dto =new UserProductDTO();
                BeanUtils.copyProperties(userProduct,dto);
                setAgentExt(dto,compId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    @Override
    public Map login(String userName, String password, int compId) throws ServiceException {
        Map retMap = new HashMap();
        try {
            password = MD5Util.MD5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CompAccount compAccount = compAccountService.get(userName, "");
        if (compAccount != null) {
            if(password.equals(compAccount.getPassword())){
                Comp comp = compService.get(compAccount.getCompId());
                retMap.put("type", 1);//公司级别登录
                retMap.put("comp", comp);
            }else {
                retMap.put("type",-997);//密码错误
            }

        } else {
            Map qryParam = new HashMap();

            qryParam.put("mobilePhone", userName);
            qryParam.put("password", password);
            Map<String, Object> user = appLoginService.qryUserInfo(qryParam);
            if(user == null){
                retMap.put("type",-999);//用户未注册
            }
            if (user != null) { //用户存在
                if(password.equals(user.get("passWord"))){
                    CompUserDTO dto = this.get(StringUtil.getInt(user.get("userId"), 0), 0, 0);
                    if (dto != null && dto.getCompId() >0) {
                        if(dto.getStatus() ==1){
                            Comp comp = compService.get(dto.getCompId());
                            retMap.put("comp", comp);
                            retMap.put("type", 2);//员工别登录
                            retMap.put("user", dto);
                        }else if(dto.getStatus() == 0){
                            retMap.put("type", -996);//公司未审核，请稍候...
                        }else if(dto.getStatus() == 2){
                            retMap.put("type", -995);//公司审核未通过...

                        }

                    }else {
                        retMap.put("type",-998);//用户未绑定该公司
                    }
                }else {
                    retMap.put("type",-997);//密码错误
                }

            }
        }
        return retMap;
    }

    @Override
    public PageDto getAgentApply(int pageNum, int rows ,int productId, int compId ,int userId) throws ServiceException {
        PageDto pageDto = new PageDto();
        List<UserApplyDTO> dtos= new ArrayList();
        UserApplyExample ex = new UserApplyExample();
        UserApplyExample.Criteria criteria = ex.createCriteria();
        criteria.andProductIdEqualTo(productId);
        criteria.andAgentUidEqualTo(userId);
        List<UserApply> list = null;
        try {
            PageHelper.startPage(pageNum,rows);
            list = readUserApplyDao.selectByExample(ex);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        if(list != null && list.size() >0){
            PageInfo pageInfo =new PageInfo(list);

            for (UserApply apply : list) {
                UserApplyDTO dto = new UserApplyDTO();
                BeanUtils.copyProperties(apply,dto);
                try {
                    setApplyExt(dto,compId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dtos.add(dto);
            }
            pageDto.setList(dtos);
            pageDto.setInfo(pageInfo);
        }
        return pageDto;
    }
}
